/*
 * BuscarAcervo.java
 *
 * Created on 22/10/2011, 20:31:29
 */
package org.acervus.gui;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import org.acervus.acervo.AcervoBean;
import org.acervus.acervo.AcervoController;
import org.acervus.acervo.TipoAcervoController;

/**
 * @author Eziel Soares, Giordano Giuliano, Lenilson Regis
 */
public class BuscarAcervo extends javax.swing.JDialog {
    
    DefaultTableModel tmAcervo = new DefaultTableModel(null, new String[]{"Título", "Autor", "Ano", "Lançamento", "Tipo"});
    ListSelectionModel lsmAcervo;
    List<AcervoBean> acervo;

    /** Creates new form BuscarAcervo */
    public BuscarAcervo() {
        initComponents();
        this.setLocationRelativeTo(null);
    }

    private void tbAcervoLinhaSelecionada() {
        if (tbAcervo.getSelectedRow() != -1) {
            
        }
    }
    
    private void listarAcervo() {
        AcervoController ace = new AcervoController();
        acervo = ace.listarAcervo("%" + tfPesquisarAcervo.getText().trim() + "%");
        mostrarAcervo(acervo);
    }
    
    private void mostrarAcervo(List<AcervoBean> acervos) {

        while (tmAcervo.getRowCount() > 0) {
            tmAcervo.removeRow(0);
        }

        if (acervos.isEmpty()) {
            JOptionPane.showMessageDialog(this, "Nenhum acervo encontrado!");
        } else {
            Date data = new Date();
            Date dataLancamento = new Date();
            String ano = "";
            String lancamento = "";
            String[] campos = new String[]{null, null, null, null, null};
            for (int i = 0; i < acervos.size(); i++) {
                tmAcervo.addRow(campos);
                tmAcervo.setValueAt(acervos.get(i).getTitulo(), i, 0);
                tmAcervo.setValueAt(acervos.get(i).getAutor(), i, 1);

                try {
                    data = new SimpleDateFormat("yyyy-MM-dd").parse(acervos.get(i).getAno());
                    ano = new SimpleDateFormat("yyyy").format(data);

                    if (acervos.get(i).getLancamento() != null) {
                        dataLancamento = new SimpleDateFormat("yyyy-MM-dd").parse(acervos.get(i).getLancamento());
                        lancamento = new SimpleDateFormat("dd/MM/yyyy").format(dataLancamento);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                tmAcervo.setValueAt(ano, i, 2);
                tmAcervo.setValueAt(lancamento, i, 3);

                TipoAcervoController tac = new TipoAcervoController();
                tmAcervo.setValueAt(tac.getTipoAcervo(Integer.parseInt(acervos.get(i).getTipo())), i, 4);
            }
        }
    }
    
    private AcervoBean retornarAcervo(){
        AcervoBean itemAcervo = new AcervoBean();
        
        if (tbAcervo.getSelectedRow() != -1) {
            AcervoController ac = new AcervoController();
            itemAcervo = ac.retornaAcervo(acervo.get(tbAcervo.getSelectedRow()).getId());
        }
        
        return itemAcervo;
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        tfPesquisarAcervo = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbAcervo = new javax.swing.JTable();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Buscar Acervo");

        jLabel1.setText("Título:");

        jButton1.setText("Pesquisar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        tbAcervo.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tbAcervo.setModel(tmAcervo);
        tbAcervo.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        lsmAcervo = tbAcervo.getSelectionModel();
        lsmAcervo.addListSelectionListener(new ListSelectionListener(){
            public void valueChanged(ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) {
                    tbAcervoLinhaSelecionada();
                }
            }
        });

        // Define o layuout da tabela
        tbAcervo.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        tbAcervo.getColumnModel().getColumn(0).setPreferredWidth(260);
        tbAcervo.getColumnModel().getColumn(1).setPreferredWidth(180);
        tbAcervo.getColumnModel().getColumn(2).setPreferredWidth(55);
        tbAcervo.getColumnModel().getColumn(3).setPreferredWidth(90);
        tbAcervo.getColumnModel().getColumn(4).setPreferredWidth(110);

        listarAcervo();
        jScrollPane1.setViewportView(tbAcervo);

        jButton2.setText("OK");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Cancelar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 701, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tfPesquisarAcervo, javax.swing.GroupLayout.DEFAULT_SIZE, 512, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton2)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(tfPesquisarAcervo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(64, 64, 64)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton3))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        listarAcervo();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        retornarAcervo();
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(BuscarAcervo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(BuscarAcervo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(BuscarAcervo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(BuscarAcervo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new BuscarAcervo().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tbAcervo;
    private javax.swing.JTextField tfPesquisarAcervo;
    // End of variables declaration//GEN-END:variables
}
